﻿using Microsoft.AspNetCore.Mvc;

namespace DailyReport.Server.Service;

/// <summary>
/// 
/// </summary>
[ApiExplorerSettings(GroupName = "WeeklyReport")]
public class WeeklyService : IApplicationService
{
    private readonly SugarRepository<ReportDetail> _thisRepository;
    private readonly ICurrentUser _currentUser;

    public WeeklyService(SugarRepository<ReportDetail> thisRepository, ICurrentUser currentUser)
    {
        _thisRepository = thisRepository;
        _currentUser = currentUser;
    }

    public async Task<RestfulResult<PageResult<ReportDetailOutDto>>> GetPagesAsync(PageParam data)
    {
        var restful = new RestfulResult<PageResult<ReportDetailOutDto>> { Code = CodeStatus.OK };

        var query = await _thisRepository.AsQueryable()
            .Where(u => u.Creator == _currentUser.UserId)
            .Where(u => u.Category == Category.Week)
            .OrderByDescending(u => u.Day)
            .Select(u => new ReportDetailOutDto
            {
                Id = u.Id,
                Day = u.Day,
                Content = u.Content,
                PlanContent = u.PlanContent,
                Week = u.Week,
            })
            .ToPageAsync(data.PageNo, data.PageSize);

        restful.Data = query;
        return restful;
    }

    public async Task<RestfulResult> SubmitAsync(ReportDetail data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };

        if (data.Week == null)
        {
            restful.Message = "周不能空";
            return restful;
        }

        if (data.Content.IsNullOrWhiteSpace())
        {
            restful.Message = "周报内容不能空";
            return restful;
        }

        bool result = false;
        if (data.Id == 0)
        {
            data.Category = Category.Week;
            data.IsDelete = IsDelete.N;
            data.Month = data.Day.Month;
            result = await _thisRepository.InsertAsync(data);
        }
        else
        {
            result = await _thisRepository.UpdateAsync(data);
        }

        if (result)
        {
            restful.Code = CodeStatus.OK;
            restful.Data = result;
        }
        else
        {
            restful.Data = result;
        }

        return restful;
    }
}